<template>
	<view>
		<tm-spin :load="load" tip="加载中" bgColor="rgba(255,255,255,0.4)" color="#2DB295">
		<o-navbarx :back="false" :isback="true" color="#000000" backgroundImage="/static/img/indexbg.png">
			<template #left_conent>
				<view class="search-container" @click="gosearch">
					<image src="/static/img/icon_sousuo.png" class="search-icon" mode=""></image>
					<view class="search-text">搜索商品名称</view>
				</view>
			</template>
		</o-navbarx>
		
		<view class="pad-lr-24 poRe index_bg_top bgf5 mar-top-16">
			<image src="/static/img/indexbg.png" class="width-100 poAb -top-0 left-0" mode="widthFix"></image>
			<!-- <o-swiper contentRadius='16rpx' :height="410" indicatorColor="#FFFFFF" :list="ad_list" indicatorActiveColor="#2DB295" @clickItem="clickItem"></o-swiper> -->
			<view class="width-100 inheight mar-top-20 radius-16 over-hid">
				<swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="1000" class="width-100 height-100" v-if="introduce">
					<swiper-item class="width-100 height-100" v-for="item in introduce.file_type==1?introduce.image_text:introduce.video_text">
						<image :src="item" v-if=" introduce.file_type==1" class="width-100 height-100" mode="aspectFill"></image>
						<video :src="item" v-if=" introduce.file_type==2" class="width-100 height-100"></video>
					</swiper-item>
				</swiper>
			</view>
			<!-- <view class="radius-16 bgfff display align-items flex-wrap pad-top-30">
				<view class="width-25 text-align-center mb30" v-for="item in category_list" :key="item.id" @click="goclass(item.id)">
					<image :src="item.image_text" class="wid-hig-88" mode=""></image>
					<view class="fontSize-26">{{item?.name}}</view>
				</view>
			</view> -->
			<view class="mar-top-20 bgF6F7FC pad-lr-20 display align-items pad-tb-12 radius-16" v-for="item in notice" :key="item.id" @click="gotxtrich(item.id)">
				<text class="fontSize-32 ml10"><text style="color: #027DFD;">公</text>告</text>
				<view class="xian ml20"></view>
				<tm-roll-notice :color="'#2a2a2c'" :transprent="true" width="500" :margin="[0,0]" :padding="[0,0]" icon="" :list="item.title"></tm-roll-notice>
				<image src="/static/img/icon_jiantou_18.png" class="wid-hig-30" mode=""></image>
			</view>
			<view class="mar-top-32 text-align-center fontSize-36">爆款商品</view>
			<view class="row a-center pad-tb-20 pad-lr-20 mar-top-30 bgfff">
				<view class="flex1 row j-sb">
					<view class="w-per25" :class="tab_index1===index?'c-333333':'c-666666'" v-for="(item,index) in tabs1" :key="index" @tap="changeTab1(index)">
						{{item.text}}
					</view>
					<view class="w-per25 row a-center" @tap="changeSort">
						<text class="mr10">价格</text>
						<view class="column a-center">
							<view class="">
								<tm-icon name="tmicon-arrow-sortdown-smal" class="trfrom" fontSize="26" :color="price_sort===0?'#333':'#D9D9D9'"></tm-icon>
							</view>
							<view class="">
								<tm-icon name="tmicon-arrow-sortdown-smal" fontSize="26" :color="price_sort===1?'#333':'#D9D9D9'"></tm-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="index_bottom_view pad-lr-24">
			<view class="display align-items mar-top-20 pad-lr-20">
				<view class="fontSize-26 pad-lr-16 pad-tb-10 poRe nav_view radius-28 bgfff" v-for="item in nav_list" :key="item.id" :class="current==item.id?'active':''" @click="change(item.id)">
					{{item?.name}}
				</view>
			</view>
			<view class="display-sb align-items flex-wrap ">
				<view class="radius-16 over-hid bgfff pad-lr-12 pad-tb-12 goods_list mar-top-20" v-for="item in goods_list" :key="item.id" @click="gogoodsdetails(item.id)">
					<image :src="item.image_text" class="wid-hig-320" mode=""></image>
					<view class="mar-top-14">
						<view class="text-clamp-2 fontSize-28">
							<text class="col-f tag_view_two radius-4 fontSize-22" v-if="item.is_limit==1">限购</text>
							{{item.name}}
						</view>
						<view class="display-sb align-items mar-top-14">
							<view class="fontSize-30 col-DB3231"><text class="fontSize-22">￥</text>{{item.price}}</view>
							<view class="col-6 fontSize-26">销量{{item.total_sales>999?'999+':item.total_sales}}</view>
						</view>
						<view class="mar-top-14 display-sb align-items fontSize-24">
							<view class="col-6 width-70 text-clamp-1">{{item?.shop?.name}}</view>
							<view class="display align-items ml6 " @click.stop="goshopgoods(item.shop.id)">
								进店
								<image src="/static/img/icon1.png" class="wid-hig-24" mode=""></image>
							</view>
						</view>
					</view>
				</view>
				<view class="display-ce align-items width-100" v-if="goods_list.length==0">
					<tm-result :showBtn="false" subTitle=" " title="暂无数据" color="#2DB295"></tm-result>
				</view>
			</view>				
		</view>
		</tm-spin>
		<!-- <view class="pad-lr-20">
			<view class="">
				<view class="bg2a pad-lr-20 pad-tb-14 radius-36 display-sb align-items mar-top-20" @click="gosearch">
					<image src="/static/img/icon_sousuo.png" class="proudct-item-icon-24" mode=""></image>
					<view class="ipt fontSize-26 col-6">搜索商品名称</view>
				</view>
			</view>
			<view class="mar-top-20 bg2a pad-lr-20 display align-items" v-for="item in notice" :key="item.id" @click="gotxtrich(item.id)">
				<image src="/static/img/gonggao.png" class="wid-hig-28" mode=""></image>
				<text class="fontSize-28 col-bc8c1e ml10">公告</text>
				<view class="xian ml20"></view>
				<tm-roll-notice :color="'#2a2a2c'" :transprent="true" width="500" :margin="[0,0]" :padding="[0,0]" fontColor="#bc8c1e" icon="" :list="item.title"></tm-roll-notice>
				<image src="/static/img/icon_jiantou_18.png" class="wid-hig-30" mode=""></image>
			</view>
			<view class=" mar-top-20">
				<view class="display" v-if="introduce">
					<view class=" poRe fontSize-40 fontBold col-bc8c1e display">
						{{introduce.title}}
						<view class="poAb bottom_border radius-4"></view>
					</view>
				</view>
				<view class="width-100 inheight mar-top-20" v-if="introduce">
					<swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="1000" class="width-100 height-100">
						<swiper-item class="width-100 height-100" v-for="item in introduce.file_type==1?introduce.image_text:introduce.video_text">
							<image :src="item" v-if=" introduce.file_type==1" class="width-100 height-100" mode="aspectFill"></image>
							<video :src="item" v-if=" introduce.file_type==2" class="width-100 height-100"></video>
						</swiper-item>
					</swiper>
				</view>
			</view>
			<view class="mar-top-30">
				<view class="display">
					<view class=" poRe fontSize-40 fontBold col-bc8c1e display">
						{{index_title}}
						<view class="poAb bottom_border radius-4"></view>
					</view>					
				</view>
				<view class="row a-center pad-tb-20 pad-lr-20 mar-top-30 bg2a">
					<view class="flex1 row j-sb">
						<view class="w-per25" :class="tab_index1===index?'col-bc8c1e':'col-f'" v-for="(item,index) in tabs1" :key="index" @tap="changeTab1(index)">
							{{item.text}}
						</view>
						<view class="w-per25 row a-center" @tap="changeSort">
							<text class="mr10 col-f">价格</text>
							<view class="column a-center">
								<view class="">
									<tm-icon name="tmicon-arrow-sortdown-smal" class="trfrom" fontSize="26" :color="price_sort===0?'#bc8c1e':'#D9D9D9'"></tm-icon>
								</view>
								<view class="">
									<tm-icon name="tmicon-arrow-sortdown-smal" fontSize="26" :color="price_sort===1?'#bc8c1e':'#D9D9D9'"></tm-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="bgf6">
					<view class="display align-items mar-top-20 pad-lr-20">
						<view class="fontSize-30 poRe nav_view" v-for="item in nav_list" :key="item.id" :class="current==item.id?'active':'col-f'" @click="change(item.id)">
							{{item?.name}}
							<view class="xian radius-4 poAb" v-show="current==item.id"></view>
						</view>
					</view>
					<view class="display-sb align-items flex-wrap mar-top-10">
						<view class="radius-16 over-hid bg2a pad-lr-12 pad-tb-12 goods_list mar-top-20" v-for="item in goods_list" :key="item.id" @click="gogoodsdetails(item.id)">
							<image :src="item.image_text" class="wid-hig-320" mode="aspectFit"></image>
							<view class="mar-top-14">
								<view class="text-clamp-2 fontSize-28">
									<text class="col-f tag_view_two radius-4 fontSize-22" v-if="item.is_limit==1">限购</text>
									<text class="col-bc8c1e">{{item.name}}</text>
								</view>
								<view class="display-sb align-items mar-top-14">
									<view class="fontSize-30 col-DB3231"><text class="fontSize-22">￥</text>{{item.price}}</view>
									<view class="col-bc8c1e fontSize-26">销量{{item.total_sales>999?'999+':item.total_sales}}</view>
								</view>
							</view>
						</view>
						<view class="display-ce align-items width-100" v-if="goods_list.length==0">
							<tm-result :showBtn="false" subTitle=" " title="暂无数据" color="#bc8c1e"></tm-result>
						</view>
					</view>					
				</view>
			</view>
		</view> -->
	</view>
</template>

<script lang="ts" setup>
import { onLoad, onReachBottom, onShareAppMessage, onShareTimeline, onShow } from '@dcloudio/uni-app';
import { ref } from 'vue';
import {index,write_off_pick,wxLogin,goodsList,getParams} from '@/utils/api'
// var QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js')
import QQMapWX from '@/utils/qqmap-wx-jssdk.min.js'
onLoad((options)=>{
	console.log('首页开始加载，options:', options)
	
	// 检查运行环境
	const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
	const isWeChat = /MicroMessenger/i.test(navigator.userAgent);
	console.log('运行环境检测:', { isIOS, isWeChat, userAgent: navigator.userAgent });
	
	// 如果是iOS微信环境，启用兼容性模式
	const isIOSWeChat = checkIOSWeChatCompatibility();
	
	try {
		console.log(decodeURIComponent(options.scene)?.includes('uid'),'aa')
		console.log(decodeURIComponent(options.scene)?.includes('pid'),'bbb')
	} catch (error) {
		console.error('scene参数解析失败:', error);
	}
	
	// 检查URL中是否有登录成功参数
	// 兼容iOS微信内置浏览器的参数解析
	let login = null, token = null, user_id = null, openid = null, pid = null, redirect = null;
	
	try {
		// 方法1：从hash中获取参数（兼容iOS微信）
		if (typeof window !== 'undefined' && window.location && window.location.hash && window.location.hash.includes('?')) {
			const hashParams = new URLSearchParams(window.location.hash.split('?')[1]);
			login = hashParams.get('login');
			token = hashParams.get('token');
			user_id = hashParams.get('user_id');
			openid = hashParams.get('openid');
			pid = hashParams.get('pid');
			redirect = hashParams.get('redirect');
			console.log('从hash中获取参数:', { login, token, user_id, openid, pid, redirect });
		}
		
		// 方法2：如果hash中没有，尝试从search中获取（兼容性）
		if ((!login || !token) && typeof window !== 'undefined' && window.location && window.location.search) {
			const urlParams = new URLSearchParams(window.location.search);
			login = urlParams.get('login');
			token = urlParams.get('token');
			user_id = urlParams.get('user_id');
			openid = urlParams.get('openid');
			pid = urlParams.get('pid');
			redirect = urlParams.get('redirect');
			console.log('从search中获取参数:', { login, token, user_id, openid, pid, redirect });
		}
		
		// 方法3：手动解析hash（备用方案，兼容iOS微信）
		if ((!login || !token) && typeof window !== 'undefined' && window.location && window.location.hash) {
			const hash = window.location.hash;
			console.log('手动解析hash:', hash);
			
			if (hash.includes('login=success') && hash.includes('token=')) {
				const tokenMatch = hash.match(/token=([^&]+)/);
				const userIdMatch = hash.match(/user_id=([^&]+)/);
				const openidMatch = hash.match(/openid=([^&]+)/);
				const pidMatch = hash.match(/pid=([^&]+)/);
				const redirectMatch = hash.match(/redirect=([^&]+)/);
				
				if (tokenMatch) {
					token = decodeURIComponent(tokenMatch[1]);
					user_id = userIdMatch ? decodeURIComponent(userIdMatch[1]) : '';
					openid = openidMatch ? decodeURIComponent(openidMatch[1]) : '';
					pid = pidMatch ? decodeURIComponent(pidMatch[1]) : '';
					redirect = redirectMatch ? decodeURIComponent(redirectMatch[1]) : '';
					login = 'success';
					console.log('手动解析结果:', { login, token, user_id, openid, pid, redirect });
				}
			}
		}
	} catch (error) {
		console.error('URL参数解析失败:', error);
		// 如果解析失败，继续执行后续逻辑，不影响页面加载
	}
	
	console.log('首页最终检测到URL参数:', { login, token, user_id, openid, pid, redirect });
	
	// 如果有登录成功参数，保存登录信息
	if (login === 'success' && token && user_id) {
		console.log('首页检测到登录成功参数，准备保存登录信息');
		saveLoginInfoFromIndex(token, user_id, openid);
		
		// 检查是否需要跳转到邀请页面
		if (redirect === 'invite' && pid) {
			console.log('检测到邀请跳转参数，准备跳转到邀请页面');
			setTimeout(() => {
				uni.reLaunch({
					url: `/pages/invite/invite?pid=${pid}&login=success&token=${token}&user_id=${user_id}&openid=${openid || ''}`
				});
			}, 1000);
			return; // 跳转到邀请页面，不继续执行后续逻辑
		}
	}
	
	// 处理邀请参数（添加错误处理）
	try {
		if(decodeURIComponent(options.scene)?.includes('uid')&&!uni.getStorageSync('token')){
			uni.setStorageSync('pid',decodeURIComponent(options.scene)?.split('uid=')[1])
			uni.redirectTo({
				url:'/pages/login/login?pid='+decodeURIComponent(options.scene)?.split('uid=')[1]
			})
			return; // 跳转到登录页面，不继续执行
		}
		if(options.pid){
			uni.setStorageSync('pid',options.pid)
			uni.redirectTo({
				url:'/pages/login/h5login?pid='+options.pid
			})
			return; // 跳转到登录页面，不继续执行
		}
	} catch (error) {
		console.error('处理邀请参数失败:', error);
		// 即使处理失败，也继续加载首页
	}
	
	// 加载首页数据
	try {
		_index(0)
	} catch (error) {
		console.error('首页数据加载失败:', error);
		// 显示错误提示，但不阻止页面渲染
		uni.showToast({
			title: '页面加载失败，请重试',
			icon: 'none',
			duration: 2000
		});
	}
})
onShareAppMessage(()=>{
	return{
		title:'',
		path: '/pages/index/index?pid='+uni.getStorageSync('id')
	}
})
onShareTimeline(()=>{
	return{
		title:'',
		path: '/pages/index/index?pid='+uni.getStorageSync('id')
	}
})
onReachBottom(()=>{
	if(page.value>1){
		_goodsList()
	}
})
onShow(()=>{

})
//首页数据
const ad_list = ref(),//轮播列表
	  category_list = ref(),//一级分类列表
	  news = ref(),//新闻
	  goods_list = ref([]),//商品列表
	  page = ref(1),
	  load = ref(true),
	  notice = ref(),
	  introduce = ref(),
	  index_title= ref()
// iOS微信兼容性检查
const checkIOSWeChatCompatibility = () => {
	const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
	const isWeChat = /MicroMessenger/i.test(navigator.userAgent);
	
	if (isIOS && isWeChat) {
		console.log('检测到iOS微信环境，启用兼容性模式');
		return true;
	}
	return false;
};

// 从首页保存登录信息
const saveLoginInfoFromIndex = (token: string, user_id: string, openid: string) => {
	console.log('首页保存登录信息:', { token, user_id, openid });
	
	try {
		// 保存登录信息到localStorage
		const loginData = {
			token: token,
			user_id: user_id || '',
			openid: openid || '',
			login_time: Date.now()
		};
		
		// 保存到localStorage（兼容iOS微信）
		try {
			if (typeof localStorage !== 'undefined') {
				localStorage.setItem('h5_login_data', JSON.stringify(loginData));
				console.log('首页已保存到localStorage:', loginData);
			}
		} catch (error) {
			console.warn('localStorage保存失败，使用uni-app存储:', error);
		}
		
		// 同时保存到uni-app的存储中，确保兼容性
		uni.setStorageSync('h5_login_data', JSON.stringify(loginData));
		console.log('首页已保存到uni-app h5_login_data:', loginData);
		
		// 保存到兼容性存储
		uni.setStorageSync('h5_token', token);
		uni.setStorageSync('h5_user_info', JSON.stringify({
			id: user_id,
			openid: openid,
			nickname: '',
			avatar: '',
			mobile: '',
			token: token
		}));
		
		console.log('首页登录信息已保存到所有存储位置');
		
		// 验证保存是否成功
		const savedH5Data = uni.getStorageSync('h5_login_data');
		let savedLocalData = null;
		try {
			if (typeof localStorage !== 'undefined') {
				savedLocalData = localStorage.getItem('h5_login_data');
			}
		} catch (error) {
			console.warn('localStorage读取失败:', error);
		}
		console.log('首页验证保存结果:', { 
			uniStorage: savedH5Data, 
			localStorage: savedLocalData 
		});
		
		// 显示登录成功提示
		uni.showToast({
			title: '登录成功',
			icon: 'success',
			duration: 1500
		});
		
	} catch (error) {
		console.error('首页保存登录信息失败:', error);
		uni.showToast({
			title: '保存登录信息失败',
			icon: 'none'
		});
	}
}

const _index =(type:number) =>{
	index().then(res=>{
		if(res.code==1){
			if(type!=1){
			introduce.value = res.data.introduce
			category_list.value = res.data.goods_class
			nav_list.value = res.data.reccategory
			notice.value = res.data.notice
			current.value = res.data.reccategory[0].id
				load.value = false
			}
			getParams({fields:'index_title'}).then(res=>{
				if(res.code==1){
					index_title.value = res.data.index_title
				}
			})
			_goodsList()
		}
	})
}
const _goodsList = () =>{
	goodsList({	page:page.value,
				limit:10,
				reccategory:current.value,
				sort:sort.value
	}).then(res=>{
		if(res.code==1){
			goods_list.value =goods_list.value.concat(res.data.goods.data)
			if(res.data.goods.data.length>0){
				page.value++
			}
		}
	})
}
const nav_list = ref([
	{name:'上新啦',id:1},
	{name:'好物精选',id:2},
	{name:'热卖好货',id:3},
	{name:'超值',id:4},
	])//推荐分类列表
const tabs1 =ref([{value:1,text:'综合'},{value:2,text:'销量'},{value:3,text:'新品'},])
const tab_index1 = ref(0)
const price_sort = ref(1)//价格排序 0升1降
const current = ref()
const address = ref()
const change = (id:number) =>{
	current.value = id
	page.value = 1
	goods_list.value = []
	_goodsList()
}
 // 宫格 筛选
 const sort = ref(1)
const changeTab1=(index)=>{
	tab_index1.value = index;
	sort.value = tabs1.value[tab_index1.value].value;
	price_sort.value = 1;
	page.value = 1;
	goods_list.value = []
	_goodsList();
}
// 价格
const changeSort=()=>{
	price_sort.value = price_sort.value===0?1:0;
	sort.value = price_sort.value===0?4:5;
	page.value = 1;
	goods_list.value = []
	_goodsList();
}
const gogoodsdetails =(id:number) =>{
	uni.navigateTo({
		url:'/indexpages/goodsDetail/goodsDetail?id='+id
	})
}
const gosearch =() =>{
	uni.navigateTo({
		url:'/indexpages/search/search'
	})
}
const clickItem =(e) =>{
	if(e.jump_type==1){
		if(e.jump_val){
			uni.navigateTo({
				url:'/indexpages/goodsDetail/goodsDetail?id='+e.jump_val
			})
		}
	}else if(e.jump_type==2){
		if(e.jump_val){
		uni.navigateTo({
			url:e.jump_val
		})
		}
	}
}
const goclass =(id:number|string) =>{
	uni.setStorageSync('classid',id)
	uni.switchTab({
		url:'/pages/classification/classification'
	})
}
const goshopgoods = (id) =>{
	uni.navigateTo({
		url:'/indexpages/shopgoods/shopgoods?id='+id
	})
}
const gotxtrich = (id)=>{
	uni.navigateTo({
		url:'/mypages/txtrich/txtrich?id='+id
	})
}
</script>

<style lang="scss">
@import 'index.scss';
</style>
